<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<title>layim</title>
	<link rel="stylesheet" href="/static/layim-v3.7.6/src/css/layui.css">
	<style>
		html{background-color: #D9D9D9;}
	</style>
</head>
<body>

<button type="button" class="layui-btn" id="logout">Logout</button>
<button type="button" class="layui-btn"><?=$id?></button>

<script src="/static/layim-v3.7.6/src/layui.js"></script>
<script src="/static/js/cookie.js"></script></script>

<script>
var fd, $, ws;
var noticeNum = 0;
var user = <?=$user?>;

layui.use('layim', function(layim){
	$ = layui.jquery;

	//基础配置 初始化接口
	layim.config({
		//初始化接口
		init: {
			url: '/user/getFriendList'
			, data: {}
		}
		//查看群员接口
		,members: {
			url: '/user/getGroupUserList'
			,type: 'get' //默认get，一般可不填
			,data: {}    //额外参数
		}
		//上传图片接口
		,uploadImage: {
			url: '/upload/image/'
			,type: 'post'
		}
		//上传文件接口
		,uploadFile: {
			url: '/upload/file/' //（返回的数据格式见下文）
			, type: 'post' //默认post
		}
		//扩展工具栏
		,tool: [{
			alias: 'code'
			, title: '代码'
			, icon: '&#xe64e;'
		}]
		,msgbox: '/user/notice' //消息盒子页面地址，若不开启，剔除该项即可
		,find: '/user/find' //发现页面地址，若不开启，剔除该项即可
		,chatLog: '/user/chatlog' //聊天记录页面地址，若不开启，剔除该项即可
		,title: '我的IM' //自定义主面板最小化时的标题
		//,brief: true //是否简约模式（若开启则不显示主面板）。一般可用于客服
		//,min: true //是否始终最小化主面板，默认false
		//,right: '0px' //用于设定主面板右偏移量。该参数可避免遮盖你页面右下角已经的bar
		//,minRight: '90px' //用户控制聊天面板最小化时、及新消息提示层的相对right的px坐标。
		,initSkin: '5.jpg' //设置初始背景，默认不开启。可设置./css/modules/layim/skin目录下的图片文件名
		,isAudio: true //开启聊天工具栏音频
		,isVideo: true //开启聊天工具栏视频
		,notice: true //是否开启桌面消息提醒，默认false
		//,voice: false //声音提醒，默认开启，声音文件为：default.mp3
		//,isfriend:true //是否开启好友
		//,isgroup:true //是否开启群组
		//,maxLength:3000 //可允许的消息最大字符长度
		//,skin: ['aaa.jpg'] //新增皮肤
	});

	//创建WebSocket
	ws = new WebSocket('ws://127.0.0.1:8484')
	ws.onopen = function(evt) {
		console.log("index websocket: connection");
	};
	ws.onclose = function(evt) {
		console.log("index websocket: onclose");
	};
	ws.onerror = function (evt, err) {
		console.log("index websocket: onerror");
	};
	ws.onmessage = function(evt) {
		console.log("index websocket: onmessage");
		if (evt.data) {
			let data = JSON.parse(evt.data);
			console.log(data);

			switch (data.type) {
				case "uid":
					//设置uid
					fd = data.uid;
					ws.send(JSON.stringify({
						type: 'setFd',
						fd: data.uid,
						user_id: user.id,
						username:user.username
					}));
					break;
				case "logout":
					//退出登录
					window.location.href = "/user/login";
					break;
				case "syncLogin":
					//好友上线提示
					console.log(data.msg);
					break;
				case "syncLogout":
					//好友下线提示
					console.log(data.msg);
					break;
				case "chat":
					//个人聊天
					layim.getMessage({
						username: data.user_name
						,avatar: data.avatar
						,id: data.user_id
						,type: "friend"
						,content: data.content
						,timestamp: new Date().getTime()
					});
					break;
				case "chatGroup":
					//群聊天
					layim.getMessage({
						username: data.user_name
						,avatar: data.avatar
						,id: data.group_id
						,type: "group"
						,content: data.content
						,timestamp: new Date().getTime()
					});
					break;
				case "msgBox":
					noticeNum += data.total;
					layim.msgbox(noticeNum);
					break;
				case "addSuccess":
					layim.addList(data.data);
					noticeNum += 1;
					layim.msgbox(noticeNum);
					break;
			}
		}
	};

	//退出登录
	document.getElementById("logout").addEventListener("click", () => {
		$.post("/user/logout", function (msg) {
			if (msg.code == 0) {
				ws.send(JSON.stringify({
					type     : "logout",
					fd       : fd,
					user_id  : user.id,
					username : user.username,
				}));
			}
		}, "json")
	})

	//监听发送消息
	layim.on('sendMessage', function(data){
	  	console.log(data)
		let Mine = data.mine;
		let To   = data.to;
		switch (To.type) {
			case "group":
				ws.send(JSON.stringify({
					type      : "chatGroup",
					user_id   : Mine.id,
					user_name : Mine.username,
					avatar    : Mine.avatar,
					group_id  : To.id,
					group_name: To.groupname,
					content   : encodeURIComponent(Mine.content)
				}));
				break;
			case "friend":
				ws.send(JSON.stringify({
					type      : "chat",
					user_id   : Mine.id,
					user_name : Mine.username,
					avatar    : Mine.avatar,
					to_id     : To.id,
					to_name   : To.username,
					content   : encodeURIComponent(Mine.content)
				}));
				break;
		}
	});

	//layim建立就绪
	layim.on('ready', function(res){
		//消息盒子提示
		if (noticeNum) layim.msgbox(noticeNum);
	});

	//触发在线状态切换
	layim.on('online', function(status){
		$.post("/user/setField", {type:'online',val: status})
	});

	//触发修改签名
	layim.on('sign', function(value){
		$.post("/user/setField", {type: 'sign',val:value})
	});


    //=============
	//监听查看群员
	layim.on('members', function(data){
		console.log(data);
	});

	//监听聊天窗口的切换
	layim.on('chatChange', function(data){
		console.log(data);
	});
});

//加好友加群
function add(t, id, gid, remark) {
	ws.send(JSON.stringify({
		type      : t == 1 ? "addFriend" : "addGroup",
		from_id   : user.id,
		to_id     : id,
		gid       : gid,
		remark    : remark,
	}));
}
//同意加好友加群
function agreeAdd(id, user, from, group) {
	ws.send(JSON.stringify({
		type      : "addAgree",
		id        : id,
		user_id   : user,
		from_id   : from,
		group_id  : group,
	}));
}
//拒绝加好友加群
function refuseAdd(id, user, from, group) {
	ws.send(JSON.stringify({
		type      : "addRefuse",
		id        : id,
		user_id   : user,
		from_id   : from,
		group_id  : group,
	}));
}
//消息已读
function read() {
	noticeNum = 0;
	$.post('/user/read');
}
</script>

<script src="/static/js/im.js"></script>
</body>
</html>
